package com.maweirdos.springSecurity.service.impl;

import com.maweirdos.springSecurity.domain.LoginUser;
import com.maweirdos.springSecurity.domain.ResponseResult;
import com.maweirdos.springSecurity.domain.User;
import com.maweirdos.springSecurity.service.LoginService;
import com.maweirdos.springSecurity.utils.JwtUtil;
import com.maweirdos.springSecurity.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * Author:  Maweirdos
 * Date:  2024/6/22 下午3:20
 * Description:  登录接口实现类
 */
@Service
public class LoginServiceImp implements LoginService {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;


    @Override
    public ResponseResult login(@RequestBody User user) {
        // 认证登录信息
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(token);
        // 若没有通过认证，则抛出异常信息
        if (Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或者密码错误");
        }
        // 认证通过，使用userId生成jwt返回
        LoginUser loginUer = (LoginUser) authenticate.getPrincipal();
        String userId = loginUer.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);


        // 把完整的用户信息存入redis，其中userid作为key，注意存入redis的时候加了前缀 login:
        Map<String, String> map = new HashMap<>();
        map.put("token",jwt);
        // 存入redis中
        redisCache.setCacheObject("login:"+userId,loginUer);
        return new ResponseResult(200,"登录成功",map);
    }

    @Override
    public ResponseResult logout() {
        //获取在JwtAuthenticationTokenFilter类写的SecurityContextHolder对象中的用户id
        UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authenticationToken.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        //根据用户id，删除redis中的token值，注意我们的key是被 login: 拼接过的，所以下面写完整key的时候要带上 longin:
        boolean b = redisCache.deleteObject("login:" + userId);
        return b?new ResponseResult(200,"注销成功"):new ResponseResult(500,"操作失败");
    }
}
